package com.wxsm.wechat.core.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.meta.InsertOnly;
import com.qcloud.cos.request.DelFileRequest;
import com.qcloud.cos.request.ListFolderRequest;
import com.qcloud.cos.request.UploadFileRequest;
import com.wxsm.wechat.core.exception.ServiceException;
import com.wxsm.wechat.util.JsonUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


/**
 * Created with Yang Huan
 * Date: 2017/5/26
 * Time: 11:39
 */
@Component
@AllArgsConstructor
public class MyCOSClientImpl implements MyCOSClient {

    private final COSClient cosClient = COSClientUtil.getInstance();
    private static final String BUCKET_NAME = "wechatimage";

    public COSResult uploadFile(String cosPath, byte[] contentBuffer) throws ServiceException {
        UploadFileRequest uploadFileRequest = new UploadFileRequest(BUCKET_NAME, cosPath, contentBuffer);
        uploadFileRequest.setInsertOnly(InsertOnly.OVER_WRITE);
        uploadFileRequest.setEnableShaDigest(true);
        String cosResult = cosClient.uploadFile(uploadFileRequest);
        cosClient.shutdown();
        return JsonUtil.fromJson(cosResult, COSResult.class);
    }

    public COSResult delFile(String cosPath) throws ServiceException {
        DelFileRequest delFileRequest = new DelFileRequest(BUCKET_NAME, cosPath);
        String cosResult = cosClient.delFile(delFileRequest);
        cosClient.shutdown();
        return JsonUtil.fromJson(cosResult, COSResult.class);
    }

    public COSResult listFolder(String cosPath) throws ServiceException {
        ListFolderRequest listFolderRequest = new ListFolderRequest(BUCKET_NAME, cosPath);
        String cosResult = cosClient.listFolder(listFolderRequest);
        cosClient.shutdown();
        return JsonUtil.fromJson(cosResult, COSResult.class);
    }

    /**
     * api的delFolder方法无效，故循环取出删除
     *
     * @param cosPath
     */
    @SuppressWarnings("unchecked")
    public void delFolder(String cosPath) throws ServiceException {
        ListFolderRequest listFolderRequest = new ListFolderRequest(BUCKET_NAME, cosPath);
        String result = cosClient.listFolder(listFolderRequest);
        COSResult cosResult = JsonUtil.fromJson(result, COSResult.class);
        if (null != cosResult) {
            List<Map> list = (List<Map>) cosResult.getData().get("infos");
            for (Map map : list) {
                String path = cosPath + map.get("name").toString();
                DelFileRequest delFileRequest = new DelFileRequest(BUCKET_NAME, path);
                cosClient.delFile(delFileRequest);
            }
        }
        cosClient.shutdown();
    }

//    public static void main(String[] args) throws ServiceException {
//        MyCOSClientImpl myCOSClient = new MyCOSClientImpl();
//        myCOSClient.delFolder("/o9X7q0MYanBu-z_ehLSbUv8w59DQ/");
//    }

}
